# xfyun_service_translter.py

import base64
import hashlib
import hmac
import json
import requests
from datetime import datetime
from settings import settings



# 配置信息
APPID = settings.IFLYTEK_APPID
APIKey = settings.IFLYTEK_APIKEY
Secret = settings.IFLYTEK_APISECRET
HOST = settings.IFLYTEK_HOST
REQUEST_URI = settings.IFLYTEK_REQUEST_URI


URL = f"https://{HOST}{REQUEST_URI}"

def http_date(dt: datetime) -> str:
    weekday = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][dt.weekday()]
    month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
             "Oct", "Nov", "Dec"][dt.month - 1]
    return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (
        weekday, dt.day, month, dt.year, dt.hour, dt.minute, dt.second
    )

def sha256_digest(data: str) -> str:
    m = hashlib.sha256(data.encode("utf-8")).digest()
    return "SHA-256=" + base64.b64encode(m).decode("utf-8")

def generate_signature(digest: str, date_str: str) -> str:
    signature_str = (
        f"host: {HOST}\n"
        f"date: {date_str}\n"
        f"POST {REQUEST_URI} HTTP/1.1\n"
        f"digest: {digest}"
    )
    signature = hmac.new(
        Secret.encode("utf-8"),
        signature_str.encode("utf-8"),
        digestmod=hashlib.sha256
    ).digest()
    signature_base64 = base64.b64encode(signature).decode("utf-8")
    return (
        f'api_key="{APIKey}", algorithm="hmac-sha256", '
        f'headers="host date request-line digest", signature="{signature_base64}"'
    )

def translate(text: str, from_lang: str, to_lang: str) -> str:
    if not (APPID and APIKey and Secret):
        raise ValueError("请先配置 APPID / APIKey / Secret")

    date_str = http_date(datetime.utcnow())

    content_b64 = base64.b64encode(text.encode("utf-8")).decode("utf-8")
    payload = json.dumps({
        "common": {"app_id": APPID},
        "business": {"from": from_lang, "to": to_lang},
        "data": {"text": content_b64}
    })

    digest = sha256_digest(payload)
    signature = generate_signature(digest, date_str)

    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "Host": HOST,
        "Date": date_str,
        "Digest": digest,
        "Authorization": signature
    }
    print(URL)
    response = requests.post(URL, data=payload, headers=headers, timeout=8)
    if response.status_code != 200:
        raise Exception(f"HTTP请求失败：{response.status_code}，{response.text}")

    resp_json = response.json()
    if resp_json.get("code") != 0:
        raise Exception(f"翻译错误：{resp_json.get('message')}")

    return resp_json["data"]["result"]
